<template>
  <div class="resume-container" v-loading="loading">
    <div style="display: flex; padding: 32px 15%">
      <el-avatar :src="userStore.userInfo.avatar" :size="68" />
      <div
        style="
          margin-left: 12px;
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
        "
      >
        <p style="font-size: 22px; width: 100%">
          {{ myResumeInfo?.realname }}
          <el-text
            type="primary"
            style="float: right; cursor: pointer"
            @click="changeResumeDialog = true"
          >
            编辑
          </el-text>
        </p>
        <div>
          <el-tag>{{ myResumeInfo?.currentCity }}</el-tag>
          <el-tag style="margin-left: 8px">
            {{ myResumeInfo?.gender == 1 ? '男' : '女' }}
          </el-tag>
          <el-tag style="margin-left: 8px">
            {{ myResumeInfo?.birthdate }}
          </el-tag>
          <el-tag style="margin-left: 8px">
            {{
              handleResumeStatus(myResumeInfo?.status ? myResumeInfo.status : 0)
            }}
          </el-tag>
        </div>
        <div style="display: flex; align-items: center">
          <el-icon>
            <Iphone />
          </el-icon>
          <span style="font-size: 14px">{{ myResumeInfo?.phone }}</span>
          <el-icon style="margin-left: 12px">
            <Message />
          </el-icon>
          <span style="font-size: 14px">{{ myResumeInfo?.email }}</span>
        </div>
      </div>
    </div>
    <div style="padding: 32px 15%">
      <p style="font-size: 18px; font-weight: bold">个人优势</p>
      <p style="padding: 20px 32px">{{ myResumeInfo?.advantage }}</p>
    </div>
    <div style="padding: 32px 15%">
      <p style="font-size: 18px; font-weight: bold">工作经历</p>
      <v-md-preview :text="myResumeInfo?.workExperience" />
    </div>
    <div style="padding: 32px 15%">
      <p style="font-size: 18px; font-weight: bold">项目经历</p>
      <v-md-preview :text="myResumeInfo?.projectExperience" />
    </div>
    <el-dialog v-model="changeResumeDialog" title="修改简历" width="880" center>
      <el-form
        :model="updateResumeForm"
        label-width="auto"
        style="min-width: 680px"
        ref="changeResumeRef"
        :rules="resumeRules"
      >
        <el-form-item label="真实姓名：" prop="realname">
          <el-input v-model="updateResumeForm.realname" style="width: 268px" />
        </el-form-item>
        <el-form-item label="性别：" prop="gender">
          <el-select v-model="updateResumeForm.gender">
            <el-option :value="1" label="男" />
            <el-option :value="2" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期：" prop="birthdate">
          <el-date-picker
            v-model="updateResumeForm.birthdate"
            type="date"
            placeholder="选择出生日期"
            :disabled-date="disabledDate"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="当前城市：" prop="currentCity">
          <el-input
            v-model="updateResumeForm.currentCity"
            style="width: 268px"
          />
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-select v-model="updateResumeForm.status">
            <el-option
              v-for="item in constantEnum.RESUME_STATUS"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话：" prop="phone">
          <el-input v-model="updateResumeForm.phone" style="width: 268px" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="updateResumeForm.email" style="width: 268px" />
        </el-form-item>
        <el-form-item label="个人优势：" prop="workExperience">
          <el-input
            v-model="updateResumeForm.advantage"
            type="textarea"
            style="width: 368px"
            show-word-limit
            :maxlength="500"
          />
        </el-form-item>
        <el-form-item label="工作经历：" prop="workExperience">
          <v-md-editor
            v-model="updateResumeForm.workExperience"
            height="400px"
          ></v-md-editor>
        </el-form-item>
        <el-form-item label="项目经历：" prop="projectExperience">
          <v-md-editor
            v-model="updateResumeForm.projectExperience"
            height="400px"
          ></v-md-editor>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitChangeResumeForm(changeResumeRef)"
          >
            修改
          </el-button>
          <el-button @click="changeResumeDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div style="padding: 32px 15%">
      <p style="font-size: 18px; font-weight: bold">
        求职期望
        <el-button
          type="primary"
          :icon="Plus"
          circle
          size="small"
          @click="showAddExpectForm = !showAddExpectForm"
        />
      </p>
      <el-dialog
        v-model="showAddExpectForm"
        title="添加求职期望"
        width="680"
        center
      >
        <el-form
          :model="addExpect"
          label-width="auto"
          style="max-width: 480px"
          ref="ruleAddExpectFormRef"
          :rules="expectRules"
        >
          <el-form-item label="职位：" prop="jobTag">
            <el-cascader
              v-model="addExpect.jobTag"
              :options="tagDatas"
              :props="customProps"
              :show-all-levels="false"
              clearable
              style="width: 128px; margin-right: 12px"
            />
          </el-form-item>
          <el-form-item label="类型：" prop="type">
            <el-select v-model="addExpect.type">
              <el-option
                v-for="item in constantEnum.JOB_TYPE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最低薪资：" prop="minSalary">
            <el-input-number
              v-model="addExpect.minSalary"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="最高薪资：" prop="maxSalary">
            <el-input-number
              v-model="addExpect.maxSalary"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="期望城市：" prop="maxSalary">
            <el-input v-model="addExpect.city" :min="0"></el-input>
          </el-form-item>
          <el-form-item label="其他城市：" prop="otherCity">
            <el-input v-model="addExpect.otherCity" :min="0"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitExpectForm(ruleAddExpectFormRef)"
            >
              保存
            </el-button>
            <el-button @click="resetExpectForm(ruleAddExpectFormRef)">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-card
        v-for="item in myResumeInfo?.expects"
        shadow="always"
        style="margin: 12px 26px"
      >
        <p>
          {{ item.jobTagName }}&nbsp; |&nbsp; {{ item.minSalary }}-{{
            item.maxSalary
          }}K &nbsp;|&nbsp; {{ item.city }} {{ item.otherCity }} &nbsp;| &nbsp;
          <el-tag type="warning">{{ handleJobType(item.type) }}</el-tag>
          <el-text
            type="primary"
            style="float: right; cursor: pointer; font-weight: bold"
            @click="openChangeExpect(item)"
          >
            编辑
          </el-text>
        </p>
      </el-card>
      <el-dialog
        v-model="showChangeExpectForm"
        title="修改求职期望"
        width="680"
        center
      >
        <el-form
          :model="changeExpect"
          label-width="auto"
          style="max-width: 480px"
          ref="ruleChangeExpectFormRef"
          :rules="expectRules"
        >
          <el-form-item label="职位：" prop="jobTag">
            <el-cascader
              v-model="changeExpect.jobTag"
              :options="tagDatas"
              :props="customProps"
              :show-all-levels="false"
              clearable
              style="width: 128px; margin-right: 12px"
            />
          </el-form-item>
          <el-form-item label="类型：" prop="type">
            <el-select v-model="changeExpect.type">
              <el-option
                v-for="item in constantEnum.JOB_TYPE"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="最低薪资：" prop="minSalary">
            <el-input-number
              v-model="changeExpect.minSalary"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="最高薪资：" prop="maxSalary">
            <el-input-number
              v-model="changeExpect.maxSalary"
              :min="0"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="期望城市：" prop="maxSalary">
            <el-input v-model="changeExpect.city" :min="0"></el-input>
          </el-form-item>
          <el-form-item label="其他城市：" prop="otherCity">
            <el-input v-model="changeExpect.otherCity" :min="0"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitChangeExpectForm(ruleChangeExpectFormRef)"
            >
              保存
            </el-button>
            <el-button @click="showChangeExpectForm = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div style="padding: 0px 15%">
      <p style="font-size: 18px; font-weight: bold">
        教育经历
        <el-button
          type="primary"
          :icon="Plus"
          circle
          size="small"
          @click="showAddEEForm = !showAddEEForm"
        ></el-button>
      </p>
      <el-card
        v-for="item in myResumeInfo?.educationExperiences"
        shadow="always"
        style="margin: 12px 26px"
      >
        <p style="font-size: 18px; font-weight: bold">
          {{ item.schoolName }}
          <el-text type="info">
            {{ item.enrollmentYear }} - {{ item.graduationYear }}
          </el-text>
          <el-text
            type="primary"
            style="float: right; cursor: pointer"
            @click="openChangeEducation(item)"
          >
            编辑
          </el-text>
        </p>
        <div style="margin-top: 8px">
          <el-tag>{{ item.major }}</el-tag>
          <el-tag>{{ item.type === 1 ? '全日制' : '非全日制' }}</el-tag>
          <el-tag>{{ handleEducationEnum(item.education) }}</el-tag>
        </div>
        <div style="margin-top: 8px" v-if="item.schoolExperience">
          <p style="font-size: 16px; font-weight: bold">在校经历</p>
          <p style="padding: 8px 32px">{{ item.schoolExperience }}</p>
        </div>
      </el-card>
      <el-dialog
        v-model="showChangeEEForm"
        title="修改教育经历"
        width="680"
        center
      >
        <el-form
          :model="changeEducationExperience"
          label-width="auto"
          style="max-width: 480px"
          ref="ruleChangeEEFormRef"
          :rules="eeRules"
        >
          <el-form-item label="学校名称：" prop="schoolName">
            <el-input v-model="changeEducationExperience.schoolName" />
          </el-form-item>
          <el-form-item label="学制类型：" prop="type">
            <el-select v-model="changeEducationExperience.type">
              <el-option label="全日制" :value="1" />
              <el-option label="非全日制" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="学历：" prop="education">
            <el-select v-model="changeEducationExperience.education">
              <el-option
                v-for="item in constantEnum.EDUCATION_ENUM"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专业：" prop="major">
            <el-input v-model="changeEducationExperience.major" />
          </el-form-item>
          <el-form-item label="入学年份：" prop="enrollmentYear">
            <el-date-picker
              v-model="changeEducationExperience.enrollmentYear"
              value-format="YYYY"
              type="year"
              placeholder="入学年份"
            />
          </el-form-item>
          <el-form-item label="毕业年份：" prop="graduationYear">
            <el-date-picker
              v-model="changeEducationExperience.graduationYear"
              value-format="YYYY"
              type="year"
              placeholder="毕业年份"
            />
          </el-form-item>
          <el-form-item label="在校经历：" prop="schoolExperience">
            <el-input
              type="textarea"
              show-word-limit
              :maxlength="200"
              v-model="changeEducationExperience.schoolExperience"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="submitChangeForm(ruleChangeEEFormRef)"
            >
              修改
            </el-button>
            <el-button @click="showChangeEEForm = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <el-dialog v-model="showAddEEForm" title="添加教育经历" width="680" center>
      <el-form
        :model="addEducationExperience"
        label-width="auto"
        style="max-width: 480px"
        ref="ruleAddEEFormRef"
        :rules="eeRules"
      >
        <el-form-item label="学校名称：" prop="schoolName">
          <el-input v-model="addEducationExperience.schoolName" />
        </el-form-item>
        <el-form-item label="学制类型：" prop="type">
          <el-select v-model="addEducationExperience.type">
            <el-option label="全日制" :value="1" />
            <el-option label="非全日制" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="学历：" prop="education">
          <el-select v-model="addEducationExperience.education">
            <el-option
              v-for="item in constantEnum.EDUCATION_ENUM"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业：" prop="major">
          <el-input v-model="addEducationExperience.major" />
        </el-form-item>
        <el-form-item label="入学年份：" prop="enrollmentYear">
          <el-date-picker
            v-model="addEducationExperience.enrollmentYear"
            value-format="YYYY"
            type="year"
            placeholder="入学年份"
          />
        </el-form-item>
        <el-form-item label="毕业年份：" prop="graduationYear">
          <el-date-picker
            v-model="addEducationExperience.graduationYear"
            value-format="YYYY"
            type="year"
            placeholder="毕业年份"
          />
        </el-form-item>
        <el-form-item label="在校经历：" prop="schoolExperience">
          <el-input
            type="textarea"
            show-word-limit
            :maxlength="200"
            v-model="addEducationExperience.schoolExperience"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleAddEEFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleAddEEFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  reqAddEducationExperience,
  reqAddExpect,
  reqChangeEducationExperience,
  reqChangeExpect,
  reqChangeResuem,
  reqGetMyResumeInfo,
} from '@/api/resume'
import {
  EducationExPerienceType,
  ExpectType,
  ResumeType,
} from '@/api/resume/type'
import {
  handleResumeStatus,
  handleEducationEnum,
  handleJobType,
  constantEnum,
} from '@/constant/type'
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import type { CascaderProps, FormInstance, FormRules } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { reqGetAllTag } from '@/api/tag'
import { TagType } from '@/api/tag/type'

onMounted(() => {
  getMyResumeInfo()
  getAllTag()
})

const myResumeInfo = ref<ResumeType>()
const userStore = useUserStore()
const loading = ref(false)

const changeResumeDialog = ref(false)
const updateResumeForm = ref<ResumeType>({
  id: 0,
  userId: 0,
  realname: '',
  gender: 0,
  birthdate: '',
  currentCity: '',
  email: '',
  phone: '',
  status: 0,
  advantage: '',
  workExperience: '',
  projectExperience: '',
})
const changeResumeRef = ref<FormInstance>()
const resumeRules = reactive<FormRules>({
  realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  birthdate: [{ required: true, message: '请选择生日日期', trigger: 'blur' }],
  status: [{ required: true, message: '请选择当前状态', trigger: 'blur' }],
  currentCity: [{ required: true, message: '请输入当前城市', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
  ],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
})

const tagDatas = ref<TagType[]>([])
const customProps: CascaderProps = {
  emitPath: false,
  expandTrigger: 'hover' as const,
  value: 'id', // 自定义当前数组的键名 - value
  label: 'name', // 自定义当前数组的键名 - label
  children: 'children', // 自定义当前数组的键名 - children
}

const showAddEEForm = ref(false)
const showChangeEEForm = ref(false)
const ruleAddEEFormRef = ref<FormInstance>()
const ruleChangeEEFormRef = ref<FormInstance>()

const showAddExpectForm = ref(false)
const showChangeExpectForm = ref(false)
const ruleAddExpectFormRef = ref<FormInstance>()
const ruleChangeExpectFormRef = ref<FormInstance>()

const addEducationExperience = ref<EducationExPerienceType>({
  resumeId: 0,
  schoolName: '',
  type: 1,
  education: 3,
  major: '',
  enrollmentYear: '',
  graduationYear: '',
  schoolExperience: '',
})

const changeEducationExperience = ref<EducationExPerienceType>({
  id: 0,
  resumeId: 0,
  schoolName: '',
  type: 1,
  education: 3,
  major: '',
  enrollmentYear: '',
  graduationYear: '',
  schoolExperience: '',
})

const addExpect = ref<ExpectType>({
  resumeId: 0,
  type: 1,
  jobTag: 3,
  city: '',
  otherCity: '',
  minSalary: 0,
  maxSalary: 0,
  industryId: 1,
  createTime: '',
})

const changeExpect = ref<ExpectType>({
  resumeId: 0,
  type: 0,
  jobTag: 0,
  jobTagName: '',
  city: '',
  otherCity: '',
  minSalary: 0,
  maxSalary: 0,
  industryId: 0,
  industryName: '',
  createTime: '',
})

const eeRules = reactive<FormRules>({
  schoolName: [{ required: true, message: '请输入学校名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择学制类型', trigger: 'blur' }],
  education: [{ required: true, message: '请选择学历', trigger: 'blur' }],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  enrollmentYear: [
    { required: true, message: '请选择入学年份', trigger: 'blur' },
  ],
  graduationYear: [
    { required: true, message: '请输入毕业年份', trigger: 'blur' },
  ],
})

const expectRules = reactive<FormRules>({
  type: [{ required: true, message: '请选择求职类型', trigger: 'blur' }],
  jobTag: [{ required: true, message: '请选择职位', trigger: 'blur' }],
  city: [{ required: true, message: '请选择期望城市', trigger: 'blur' }],
  minSalary: [{ required: true, message: '请输入最低薪资', trigger: 'blur' }],
  maxSalary: [{ required: true, message: '请选择最高薪资', trigger: 'blur' }],
})

const getMyResumeInfo = async () => {
  try {
    loading.value = true
    const { data } = await reqGetMyResumeInfo()
    myResumeInfo.value = data.data
    updateResumeForm.value = data.data
  } catch (e) {
    ElMessage.error((e as Error).message)
  } finally {
    loading.value = false
  }
}

const submitChangeResumeForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const { data } = await reqChangeResuem(updateResumeForm.value)
        ElMessage.success(data.message)
        getMyResumeInfo()
        changeResumeDialog.value = false
      } catch (e) {
        ElMessage.error((e as Error).message)
      }
    }
  })
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        addEducationExperience.value.resumeId = myResumeInfo.value
          ? myResumeInfo.value.id
          : 0
        const { data } = await reqAddEducationExperience(
          addEducationExperience.value,
        )
        ElMessage.success(data.message)
        formEl.resetFields()
        showAddEEForm.value = false
      } catch (e) {
        ElMessage.error((e as Error).message)
      }
    }
  })
}

const submitChangeForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const { data } = await reqChangeEducationExperience(
          changeEducationExperience.value,
        )
        ElMessage.success(data.message)
        showChangeEEForm.value = false
      } catch (e) {
        ElMessage.error((e as Error).message)
      }
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  showAddEEForm.value = false
}

const submitExpectForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        addExpect.value.resumeId = myResumeInfo.value
          ? myResumeInfo.value.id
          : 0
        const { data } = await reqAddExpect(addExpect.value)
        ElMessage.success(data.message)
        formEl.resetFields()
        showAddExpectForm.value = false
      } catch (e) {
        ElMessage.error((e as Error).message)
      }
    }
  })
}

const submitChangeExpectForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const { data } = await reqChangeExpect(changeExpect.value)
        ElMessage.success(data.message)
        showChangeExpectForm.value = false
      } catch (e) {
        ElMessage.error((e as Error).message)
      }
    }
  })
}

const resetExpectForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  showAddExpectForm.value = false
}

const openChangeEducation = (data: EducationExPerienceType) => {
  showChangeEEForm.value = true
  changeEducationExperience.value = data
}

const openChangeExpect = (data: ExpectType) => {
  showChangeExpectForm.value = true
  changeExpect.value = data
}

const getAllTag = async () => {
  let storageTag = sessionStorage.getItem('allTag')
  if (storageTag != null) {
    tagDatas.value = JSON.parse(storageTag)
    return
  }
  try {
    const { data } = await reqGetAllTag()
    sessionStorage.setItem('allTag', JSON.stringify(data.data))
    tagDatas.value = data.data
  } catch (e) {
    ElMessage.error((e as Error).message)
  }
}

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
</script>
<style scoped lang="scss">
.resume-container {
  max-width: 100vw;
  min-width: 1200px;
}
</style>
